package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {


    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Role> selectAll() {
        List<Role> roles = roleMapper.selectAll();
        return roles;
    }

    @Override
    public PageInfo<Role> selectByQo(QueryObject qo) {


        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> list = roleMapper.selectAll();
        PageInfo<Role> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Role selectById(Long roleId) {
        Role role = roleMapper.selectByPrimaryKey(roleId);
        return role;
    }

    @Override
    public void saveOrUpdate(Role role, Long[] ids) {
        //判断传过来的对象id是否为空
        if (role.getId() == null) {//表示新增
            roleMapper.insert(role);

        } else {//表示修改
            //删除旧关系
            roleMapper.deleteRelationByRoleId(role.getId());
            //修改角色信息
            roleMapper.updateByPrimaryKey(role);
        }
        if(ids!=null){
            //添加新关系
            for (Long roleId : ids) {
                if (roleId != null) {
                    roleMapper.insertRelation(role.getId(), roleId);
                }
            }
        }
    }

    @Override
    public void deleteById(Long roleId) {
        //删除关系
        roleMapper.deleteRelationByRoleId(roleId);
        //删除角色信息
        roleMapper.deleteByPrimaryKey(roleId);


    }

}

